import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  private logger = new Logger('HTTP');

  use(req: Request, res: Response, next: NextFunction) {
    const start = Date.now();
    const { method, originalUrl, ip } = req;
    
    // 记录请求开始
    this.logger.log(`[${method}] ${originalUrl} - IP: ${ip}`);
    
    // 监听响应结束事件
    res.on('finish', () => {
      const end = Date.now();
      const statusCode = res.statusCode;
      const responseTime = end - start;
      
      // 根据状态码设置日志级别
      if (statusCode >= 500) {
        this.logger.error(`[${method}] ${originalUrl} - Status: ${statusCode} - Time: ${responseTime}ms`);
      } else if (statusCode >= 400) {
        this.logger.warn(`[${method}] ${originalUrl} - Status: ${statusCode} - Time: ${responseTime}ms`);
      } else {
        this.logger.log(`[${method}] ${originalUrl} - Status: ${statusCode} - Time: ${responseTime}ms`);
      }
    });

    next();
  }
}